package app.service.sys;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import app.model.sys.SysUser;
import app.util.StringUtil;
import base.PageInfo;
import base.service.BaseService;

@Repository
public class SysUserService extends BaseService<SysUser> {

	public List<Map<String,Object>> queryLoginUserList() {
		String sql = "select * from Sys_User";
		List<Map<String,Object>> queryListBySql = getDao().queryListBySql(sql);
		return queryListBySql;
	}

	public SysUser login(String account, String password) throws Exception {
		String hql = "select o from SysUser o where o.account = '"+account+"'";
		SysUser entity = getDao().queryEntityByHQL(hql);
		if(entity==null){
			throw new Exception("账号不存在!");
		}
		String dbPassword = entity.getPassword();
		if(!password.equals(dbPassword)){
			throw new Exception("密码错误!");
		}
		return entity;
	}

	public void register(SysUser sysUser) throws Exception {
		String id = sysUser.getId();
		if(StringUtil.isEmpty(id)){
			String sql = "select * from Sys_User a where a.account = '"+sysUser.getAccount()+"'";
			List<Map<String,Object>> queryListBySql = getDao().queryListBySql(sql);
			if(queryListBySql!=null && queryListBySql.size()>0){
				throw new Exception("账号已经存在!");
			}
			getDao().save(sysUser);
		}else{
			getDao().mergeAndUpdate(sysUser);
		}
	}

	public PageInfo queryLoginUserPage(PageInfo pageInfo) {
		String sql = "SELECT a.*,b.org_name FROM Sys_User a,sys_organization b WHERE a.org_id=b.id";
		PageInfo page = getDao().queryPageListBySql(pageInfo, sql);
		return page;
	}

	public void del(String ids) throws Exception {
		if(!StringUtils.isEmpty(ids)){
			String[] idsArray = ids.split(",");
			for (int i = 0; i < idsArray.length; i++) {
				SysUser gb = getDao().queryEntityById(idsArray[i], SysUser.class);
				getDao().del(gb);
			}
		}
	}

	public SysUser queryEntityById(String id) {
		return getDao().queryEntityById(id,SysUser.class);
	}

	public void saveEntity(SysUser sysUser) {
		getDao().save(sysUser);
	}

	public void updateEntity(SysUser sysUser) {
		getDao().mergeAndUpdate(sysUser);
	}

}
